<template>
  <el-card class="box-card" shadow="never">
    <div slot="header" class="clearfix">
      <div class="head-container-whole">
        <div class="table_title">项目列表</div>
        <div class="search-el">
          <div class="select">
            <el-select v-model="query.dicItemCategory" placeholder="项目类别" size="small" class="filter-item"
              style="maxWidth: 200px" @change="crud.toQuery" clearable>
              <el-option v-for="(item, index) in categoryList" :key="index" :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </div>
          <div class="select">
            <el-input v-model="query.treatmentNameOrRef" placeholder="项目名称" size="small" class="filter-item"
              style="maxWidth: 200px" @keyup.enter.native="crud.toQuery" clearable />
          </div>
        </div>
        <div class="search-btn">
          <rrOperation class="btn" title="查询" />
          <crudOperation class="btn" :permission="permission" />
          <el-button class="btn" v-permission="permission.edit" size="mini" type="primary" @click="edit(editVal)">编辑</el-button>
        </div>
        <!-- <el-row :gutter="5" style="marginTop: 9px">
          <el-col :span="24 / 4"><rrOperation title="查询" /></el-col>
          <el-col :span="24 / 4"><crudOperation style="marginTop: -3px" :permission="permission" /></el-col>
          <el-col :span="24 / 4"><el-button style="marginTop: 1px" v-permission="permission.edit" size="mini" type="primary" @click="edit(editVal)">编辑</el-button></el-col>
        </el-row> -->
      </div>
    </div>
    <el-dialog append-to-body :close-on-click-modal="false" :before-close="crud.cancelCU"
      :visible.sync="crud.status.cu > 0" title="治疗单项维护" width="720px">
      <el-form ref="form" :inline="true" :model="form" :rules="rules" size="small" label-width="100px">
        <el-form-item label="项目名称" prop="treatmentName">
          <el-input v-model="form.treatmentName" placeholder="请输入项目名称" clearable style="width: 540px" />
        </el-form-item>
        <el-form-item label="项目类别" prop="dicItemCategory">
          <el-select v-model="form.dicItemCategory" placeholder="请选择项目类别" clearable>
            <el-option v-for="(item, index) in categoryList" :key="index" :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="执行科室" prop="departmentCode">
          <el-select v-model="form.departmentCode" placeholder="请选择执行科室" clearable>
            <el-option v-for="(item, index) in departmentList" :key="index" :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="使用类别" prop="useType">
          <el-radio-group v-model="form.useType" style="width: 540px">
            <el-radio :label="1">门诊</el-radio>
            <el-radio :label="2">住院</el-radio>
            <el-radio :label="3">通用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="项目单位" prop="dicItemUnit">
          <el-select v-model="form.dicItemUnit" placeholder="请选择项目单位" clearable>
            <el-option v-for="(item, index) in unitsList" :key="index" :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="执行疗程" prop="exePeriod">
          <el-input placeholder="请输入执行疗程" v-model="form.exePeriod" type="number" min="0" clearable style="width: 215px">
            <template slot="append">疗程</template>
          </el-input>
        </el-form-item>
        <el-form-item label="疗程次数" prop="periodNum">
          <el-input placeholder="请输入疗程次数" v-model="form.periodNum" type="number" min="0" clearable>
          </el-input>
        </el-form-item>
        <el-form-item label="执行间隔" prop="exeInterval">
          <el-input placeholder="请输入执行间隔" v-model="form.exeInterval" type="number" min="0" clearable
            style="width: 215px">
            <template slot="append">天</template>
          </el-input>
        </el-form-item>
        <el-form-item label="评估关联" prop="treatmentEstimate">
          <el-select v-model="form.treatmentEstimate" placeholder="请选择评估关联" multiple style="width: 540px">
            <el-option v-for="(item, index) in estimateList" :key="index" :label="item.label" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="单价" name="unitPrice" v-if="crud.status.edit == 1">
          <el-input placeholder="请输入单价" v-model="form.unitPrice" disabled />
        </el-form-item>
        <el-form-item label=" ">
          <a-checkbox-group v-model:value="form.checks" style="width: 100%">
            <a-checkbox :value="1">注销</a-checkbox>
            <a-checkbox :value="2">高风险</a-checkbox>
            <a-checkbox :value="3" v-if="crud.status.add == 1">高压氧</a-checkbox>
          </a-checkbox-group>
        </el-form-item>
        <el-form-item label="风险提示" prop="riskDesc" :rules="getState(2)
          ? [{ required: true, message: '请输入风险提示', trigger: 'blur' }]
          : []
          ">
          <a-input style="width: 520px" v-model="form.riskDesc" placeholder="请输入" type="textarea" clearable></a-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="crud.cancelCU">取消</el-button>
        <el-button :loading="crud.status.cu === 2" type="primary" @click="submitClick">保存</el-button>
      </div>
    </el-dialog>
    <el-table ref="table" v-loading="crud.loading" :data="crud.data[crud.listName]" highlight-current-row
      @current-change="handleCurrentChange">
      <el-table-column label="序号" width="60px" prop="indexNumber">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column :show-overflow-tooltip="true" prop="treatmentName" label="项目名称" />
      <el-table-column prop="departmentName" label="执行科室">
        <template slot-scope="scope">
          {{ scope.row.departmentName }}
        </template>
      </el-table-column>
      <el-table-column prop="dicItemCategoryName" label="项目类别" />
      <el-table-column prop="riskStates" label="高风险">
        <template slot-scope="scope">
          {{ scope.row.riskStates == 1 ? "是" : "否" }}
        </template>
      </el-table-column>
      <el-table-column prop="treatmentStates" label="注销">
        <template slot-scope="scope">
          <div class="switch">
            <el-switch v-model="scope.row.treatmentStates" :active-value="0" :inactive-value="1" :disabled="false"
              active-color="#409EFF" inactive-color="#F56C6C"
              @change="changeEnabled(scope.row, scope.row.treatmentStates)" />
            <span>{{
              scope.row.treatmentStates == 1
                ? "注销"
                : scope.row.treatmentStates == 0
                  ? "激活"
                  : ""
            }}</span>
          </div>
        </template>
      </el-table-column>
      <!-- <el-table-column
        v-permission="['admin', 'treatment/add', 'treatment/delete']"
        label="操作"
        width="130px"
        align="center"
        fixed="right"
      >
        <template slot-scope="scope">
          <div class="btn">
            <el-button
              v-permission="permission.edit"
              style="margin-right: 5px"
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="edit(scope.row)"
            ></el-button>
            <udOperation
              :disabledEdit="true"
              :data="changeSelectVal(scope.row)"
              :permission="permission"
              msg="确定删除吗,如果存在计费项目则一并删除，此操作不能撤销！"
            />
          </div>
        </template>
      </el-table-column> -->
    </el-table>
    <pagination />
  </el-card>
</template>

<script>
import treatment from "@/api/treatmentProject/treatment";
import CRUD, { presenter, header, form, crud } from "@crud/crud";
import rrOperation from "@crud/RR.operation";
import crudOperation from "@crud/CRUD.operation";
import udOperation from "@crud/UD.operation";
import pagination from "@crud/Pagination";

import {
  searchDic,
  getDepartment,
  updateTreatment,
  getEstimate,
} from "@/api/treatmentProject/treatments";
const defaultForm = {
  treatmentId: null,
  treatmentNameOrRef: null,
  treatmentName: null,
  departmentCode: null,
  dicItemCategory: null,
  useType: null,
  dicItemUnit: null,
  exePeriod: 1,
  periodNum: 1,
  exeInterval: 1,
  treatmentEstimate: null,
  unitPrice: 0,
  treatmentStates: 0,
  riskStates: 0,
  highOxygenStates: 0,
  riskDesc: null,
  checks: [],
};
export default {
  name: "singleLeft",
  components: { crudOperation, rrOperation, udOperation, pagination },
  cruds() {
    return CRUD({
      title: "治疗单项",
      url: "admin/treatment/list",
      crudMethod: { ...treatment },
      optShow: {
        reset: false,
        add: true,
        edit: false,
        del: false,
        download: false,
        opts: true,
      },
      idField: "treatmentId",
    });
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  props: {
    activeRow: {
      type: Object,
      default: null,
    },
  },
  data() {
    return {
      permission: {
        add: ["admin", "treatment/add"],
        edit: ["admin", "treatment/add"],
        del: ["admin", "treatment/delete"],
      },
      rules: {
        dicItemCategory: [
          { required: true, message: "请输入项目类别", trigger: "blur" },
        ],
        departmentCode: [
          { required: true, message: "请选择执行科室", trigger: "change" },
        ],
        treatmentName: [
          { required: true, message: "请输入项目名称", trigger: "blur" },
        ],
        useType: [
          { required: true, message: "请选择使用类别", trigger: "change" },
        ],
        dicItemUnit: [
          { required: true, message: "请选择项目单位", trigger: "change" },
        ],
        exePeriod: [
          { required: true, message: "请输入执行疗程", trigger: "blur" },
        ],
        periodNum: [
          { required: true, message: "请输入疗程次数", trigger: "blur" },
        ],
        exeInterval: [
          { required: true, message: "请输入执行间隔", trigger: "blur" },
        ],
        // treatmentEstimate: [
        //   {
        //     required: true,
        //     message: "请选择请选择评估关联",
        //     trigger: "change",
        //   },
        // ],
        unitPrice: [{ required: true, message: "请输入单价", trigger: "blur" }],
        // riskDesc: [{ required: true, message: "请输入", trigger: "blur" }],
      },
      currentRow: null,
      categoryList: [],
      unitsList: [],
      departmentList: [],
      estimateList: [],
      editVal: {},
    };
  },
  watch: {
    activeRow: function (val, oldVal) {
      this.currentRow = val;
      if (this.currentRow !== null) {
        this.$refs.table.setCurrentRow(val);
      }
    },
  },
  async mounted() {
    await this.getOption();
    await this.getDepartmentList();
    await this.getEstimateList();
  },
  methods: {
    changeSelectVal(data) {
      return {
        ...data,
        treatmentEstimate: data.treatmentEstimate.map((item) => {
          return { ...item, label: item.estimateName, value: item.estimateId };
        }),
      };
    },
    submitClick() {
      this.form.treatmentStates = this.getFloat(1) ? 1 : 0;
      this.form.riskStates = this.getFloat(2) ? 1 : 0;
      this.form.highOxygenStates = this.getFloat(3) ? 1 : 0;
      this.crud.submitCU();
    },
    getFloat(index) {
      let float = this.form.checks.some((item) => {
        return item == index;
      });
      return float;
    },
    edit(data) {
      data.checks = [
        data.treatmentStates ? 1 : null,
        data.riskStates ? 2 : null,
        data.highOxygenStates ? 3 : null,
      ];
      data.treatmentEstimate = data.treatmentEstimate.map((item) => {
        return {
          ...item,
          label: item.estimateName,
          value: item.estimateId,
        };
      });
      this.crud.toEdit(data);
    },
    getState(index) {
      return this.form.checks.includes(index);
    },
    handleCurrentChange(val) {
      this.editVal = val;
      this.$emit("change", val);
    },
    async getOption() {
      await searchDic({ dicCode: "dicItemCategory,dicItemUnit" }).then(
        (res) => {
          let self = res.content;
          self.forEach((element, elIndex) => {
            if (element.dicCode == "dicItemCategory") {
              this.categoryList = self[elIndex].itemList.map((item) => {
                return {
                  label: item.itemName,
                  value: item.itemId,
                };
              });
            }
            if (element.dicCode == "dicItemUnit") {
              this.unitsList = self[elIndex].itemList.map((item) => {
                return {
                  label: item.itemName,
                  value: item.itemId,
                };
              });
            }
          });
        }
      );
    },
    async getDepartmentList() {
      await getDepartment({
        page: 1,
        size: 999,
      }).then((res) => {
        this.departmentList = res.content.map((item) => {
          return {
            label: item.departmentName,
            value: item.departmentCode,
          };
        });
      });
    },
    async getEstimateList() {
      await getEstimate({}).then((res) => {
        this.estimateList = res.content.map((item) => {
          return {
            ...item,
            label: item.estimateName,
            value: item.estimateId,
          };
        });
      });
    },
    // 改变状态
    changeEnabled(data, val) {
      const displayName = val === 1 ? "注销" : "激活";
      this.$confirm(
        '此操作将 "' + displayName + '" ' + data.treatmentName + ", 是否继续？",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          updateTreatment({
            treatmentId: data.treatmentId,
            treatmentStates: data.treatmentStates,
          })
            .then((res) => {
              this.crud.notify(
                displayName + "成功",
                CRUD.NOTIFICATION_TYPE.SUCCESS
              );
            })
            .catch(() => {
              data.treatmentStates = data.treatmentStates === 0 ? 1 : 0;
            });
        })
        .catch(() => {
          data.treatmentStates = data.treatmentStates === 0 ? 1 : 0;
        });
    },
    [CRUD.HOOK.afterRefresh](crud) {
      if (crud.data && crud.data.content && crud.data.content.length) {
        if (this.currentRow) {
          const existRow = crud.data.content.find(
            (row) => row.treatmentId === this.currentRow.treatmentId
          );
          if (!existRow) {
            this.$emit("change", crud.data.content[0]);
          }
        } else {
          this.$emit("change", crud.data.content[0]);
        }
      }
    },
  },
};
</script>

<style lang="scss" scoped>
/deep/.crud-opts {
  display: inline-flex;
}

.table_title {
  display: inline-block;
  line-height: 30px;
  margin: 0 10px 0 0;
  vertical-align: middle;
  font-weight: bold;
  color: #303133;
  font-size: 15px;
}

.head-container-whole {
  padding-bottom: 0;
  // display: flex;
  // flex-wrap: wrap;

  /deep/.filter-item {
    margin-bottom: 0;
  }

  .search-el{
    display: flex;
    .select{
      margin-right: 5px;
    }
  }

  .search-btn{
    margin-top: 3px;
    .btn{
      display: inline-block;
      margin-right: 5px;
    }
  }
}

.switch {
  display: flex;

  span {
    margin-left: 5px;
    display: inline-block;
    min-width: 30px;
  }
}

.btn {
  display: flex;
}
</style>
